package cn.lccabc.characterString.no0049;

import java.util.*;

/**
 * @program: leet-code
 * @description: 字母异位词分组
 * 给定一个字符串数组，将字母异位词组合在一起。字母异位词指字母相同，但排列不同的字符串。
 *
 * 示例:
 *
 * 输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
 * 输出:
 * [
 *   ["ate","eat","tea"],
 *   ["nat","tan"],
 *   ["bat"]
 * ]
 * 说明：
 *
 * 所有输入均为小写字母。
 * 不考虑答案输出的顺序。
 *
 * @author: LiCC
 * @create: 2020-01-11 20:36
 */
public class Solution {

    public static List<List<String>> groupAnagrams(String[] strs) {
//        Map<String, List<String>> map = new HashMap<>();
//        for (String str : strs){
//            char[] ch = str.toCharArray();
//            Arrays.sort(ch);
//            String key = String.valueOf(ch);
//            if (!map.containsKey(key)) map.put(key, new ArrayList<>());
//            map.get(key).add(str);
//        }
//        return new ArrayList<>(map.values());

        int[] count = new int[26];
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs){
            Arrays.fill(count, 0);
            for (char c : str.toCharArray()){
                count[c - 'a']++;
            }
            StringBuffer key = new StringBuffer();
            for (int c : count){
                key.append("#").append(c);
            }
            if (!map.containsKey(key.toString())) map.put(key.toString(), new ArrayList<>());
            map.get(key.toString()).add(str);
        }
        return new ArrayList<>(map.values());
    }

    public static void main(String[] args) {
        String[] strs = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> result = groupAnagrams(strs);
        for (List<String> list : result){
            for (String str : list){
                System.out.print(str + ", ");
            }
            System.out.println("");
        }
    }
}
